package com.hup.utils.io.netty.handler.dataListener;


import com.hup.utils.io.netty.handler.DataCodecHandler;
import com.hup.utils.io.netty.model.BaseDataPacket;
import lombok.Getter;

/**
 * 记录[收发数据]占用网速的处理器;
 * 根据帧数据格式 {@link DataCodecHandler},每帧数据的长度=4*3字节+数据字节数(数据长度)
 *
 * @author hugan
 * @date 2021/5/9
 */
public class NetSpeedListener implements IDataListener {
    /**
     * 帧头,类型,数据长度,三个int占用12字节
     */
    private static final int EXTRA_LENGTH = 12;

    private static final int SUM_LIMIT = Integer.MAX_VALUE;

    private long sumReceiveLength = 0;
    private long sumSendLength = 0;

    /**
     * 网速,单位 KB/s
     */
    @Getter
    private int receiveSpeed;
    @Getter
    private int sendSpeed;
    private long lastUpdateTime;

    public NetSpeedListener() {
        lastUpdateTime = System.currentTimeMillis();
    }

    @Override
    public void onReceived(BaseDataPacket packet, int dataLength) {
        sumReceiveLength += (EXTRA_LENGTH + dataLength);
        if (sumReceiveLength > SUM_LIMIT) updateSpeed();
    }

    @Override
    public void onSend(BaseDataPacket packet, int dataLength) {
        sumSendLength += (EXTRA_LENGTH + dataLength);
        if (sumSendLength > SUM_LIMIT) updateSpeed();
    }

    public void updateSpeed() {
        long cur = System.currentTimeMillis();
        long second = (cur - lastUpdateTime) / 1000;//距离上次更新的间隔
        if (second == 0) second = 1;

        int kb = (int) (sumReceiveLength / 1024);
        receiveSpeed = (int) (kb / second);//当前时间区间内的网速
        sumReceiveLength = 0;//重置sum

        kb = (int) (sumSendLength / 1024);
        sendSpeed = (int) (kb / second);
        sumSendLength = 0;
        lastUpdateTime = cur;
    }

}
